package com.zhengb.algorithmdemo.basic.stack;

import java.util.*;

/**
 * @author zhengbo
 * @date 2020/2/18
 */
public class LinkListBaseStack<T> {

    private LLNode<T> headNode;

    public LinkListBaseStack() {
        this.headNode = new LLNode<>(null);
    }

    public void push(T data) {

        if (headNode == null) {
            headNode = new LLNode<>(data);
        } else if (headNode.getData() == null) {
            headNode.setData(data);
        } else {
            LLNode<T> insertNode = new LLNode<>(data);

            insertNode.setNextNode(headNode);
            //成为栈顶
            headNode = insertNode;
        }
    }

    public T top() {

        return headNode == null ? null : headNode.getData();
    }

    public T bottom() {

        if (headNode == null) {
            return null;
        }

        if (headNode.getNextNode() == null) {
            return headNode.getData();
        }

        LLNode<T> curNode = headNode;
        while ((curNode = curNode.getNextNode()) != null) {

            if (curNode.getNextNode() == null) {
                return curNode.getData();
            }
        }

        return null;
    }

    public T pop() {
        if (headNode == null) {
            throw new EmptyStackException();
        } else {
            T data = headNode.getData();
            headNode = headNode.getNextNode();

            return data;
        }
    }

    public int stackLength() {

        if (headNode == null) {
            return 0;
        }

        int length = 1;

        LLNode<T> curNode = headNode;

        while ((curNode = curNode.getNextNode()) != null) {
            length++;
        }

        return length;
    }

    public boolean isEmpty() {
        return headNode == null;
    }

    public void deleteStack() {

        headNode = null;
    }

    public List<T> getStackList() {

        if (headNode == null) {
            return Collections.emptyList();
        }

        List<T> stackList = new ArrayList<>();

        LLNode<T> curNode = headNode;

        stackList.add(curNode.getData());

        while ((curNode = curNode.getNextNode()) != null) {
            stackList.add(curNode.getData());
        }

        return stackList;
    }

    public static void main(String[] args) {

        LinkListBaseStack<Integer> stack = new LinkListBaseStack<>();

        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);

        System.out.println(stack.isEmpty());

        System.out.println(stack.stackLength());

        System.out.println(stack.getStackList());


        System.out.println(stack.top());
        System.out.println(stack.bottom());

        System.out.println(stack.pop());

        System.out.println(stack.top());
        System.out.println(stack.bottom());

        System.out.println(stack.getStackList());

        System.out.println(stack.stackLength());

    }

}
